package com.jz.yanshe.ui;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.FileProvider;
import android.util.LongSparseArray;
import android.view.MotionEvent;

import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;
import com.jz.jd.rest.response.GoodsTabResponse;
import com.jz.yanshe.base.BaseActivity;
import com.jz.yanshe.dialog.UpdateFragment;
import com.jz.yanshe.ui.fragment.MallFragment;
import com.jz.yanshe.ui.fragment.MineFragment;
import com.jz.yanshe.ui.fragment.RedFragment;

import com.jz.yanshe.eventbus.FragmentTabEvent;
import com.jz.yanshe.ui.fragment.ShoppingBagFragment;
import com.jz.jd.rest.business.RestProxy;
import com.jz.jd.rest.response.ConfigResponse;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

import com.jz.yanshe.util.PreferencesHelper;

import com.jz.yanshe.R;

/**
 * Created by Administrator on 2018/2/26.
 */

public class HomeActivity extends BaseActivity implements BottomNavigationBar.OnTabSelectedListener {

    //    @BindView(R.id.bottom_navigation_bar)
    BottomNavigationBar bottomNavigationBar;

//    @BindView(R.id.btn_kefu)
//    TextView btn_kefu;

    private ArrayList<Fragment> fragments;
    private Handler myHandler = new Handler();
    private UpdateFragment updateFragment;


    int payment_credential_state = -100;

    String apkUrl;
    private LongSparseArray<String> mApkPaths;
    DownloadFinishReceiver mReceiver;

    @Override
    protected void initViews() {
        bottomNavigationBar = findViewById(R.id.bottom_navigation_bar);
        bottomNavigationBar.setMode(BottomNavigationBar.MODE_FIXED);
        bottomNavigationBar
                .setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_STATIC
                );
        bottomNavigationBar.addItem(new BottomNavigationItem(R.mipmap.icon_bottom_mall1, "商城").setActiveColor("#C0A77F")).setInActiveColor("#333333")
                .addItem(new BottomNavigationItem(R.mipmap.icon_bottom_vipcenter1, "发现").setActiveColor("#C0A77F")).setInActiveColor("#333333")
                .addItem(new BottomNavigationItem(R.mipmap.iocn_bottom_buycar1, "购物袋").setActiveColor("#C0A77F")).setInActiveColor("#333333")
                .addItem(new BottomNavigationItem(R.mipmap.icon_bottom_mine, "我的").setActiveColor("#C0A77F")).setInActiveColor("#333333")
                .setFirstSelectedPosition(0)
                .initialise();

        fragments = getFragments();
        setDefaultFragment();
        bottomNavigationBar.setTabSelectedListener(this);
    }

    @Override
    protected void initData() {
        getConfigList();
        mApkPaths = new LongSparseArray<>();
        mReceiver = new DownloadFinishReceiver();
        registerReceiver(mReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }


    @Override
    protected int getLayoutResource() {
        return R.layout.activity_home;
    }


    /**
     * 设置默认的
     */
    private void setDefaultFragment() {
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        transaction.replace(R.id.layFrame, MallFragment.newInstance(getIntent().getExtras()));
        transaction.commit();
    }


    private ArrayList<Fragment> getFragments() {
        ArrayList<Fragment> fragments = new ArrayList<>();
        fragments.add(MallFragment.newInstance(getIntent().getExtras()));
        fragments.add(RedFragment.newInstance());
        fragments.add(ShoppingBagFragment.newInstance());
        fragments.add(MineFragment.newInstance());
        return fragments;
    }


    @Override
    public void onTabSelected(int position) {
        if (position != 0) {
            if (PreferencesHelper.getInstance().getString(this, "token") == null || PreferencesHelper.getInstance().getString(this, "token").equals("")) {
                toLogin(2);
                myHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        bottomNavigationBar.selectTab(0);
                    }
                }, 200);
                return;
            }
        }


//            if (position == 2) {
//                if (PreferencesHelper.getInstance().getString(this, "user_type") == null || PreferencesHelper.getInstance().getString(this, "user_type").equals("") ) {
//                    toLogin(2);
//                    return;
//                }
//                if(PreferencesHelper.getInstance().getString(this, "user_type").equals("1")){
//
//                }
//            }
//        }


        if (fragments != null) {
            if (position < fragments.size()) {
                FragmentManager fm = getSupportFragmentManager();
                FragmentTransaction ft = fm.beginTransaction();
                Fragment fragment = fragments.get(position);
                if (fragment.isAdded()) {
                    ft.replace(R.id.layFrame, fragment);
                } else {
                    ft.add(R.id.layFrame, fragment);
                }
                ft.commitAllowingStateLoss();
            }
        }

//        if (position != 0) {
//            if (PreferencesHelper.getInstance().getString(this, "token") == null || PreferencesHelper.getInstance().getString(this, "token").equals("")) {
//                onTabSelected(0);
//            }
//            if (position == 2) {
//                if (PreferencesHelper.getInstance().getString(this, "user_type") == null || PreferencesHelper.getInstance().getString(this, "user_type").equals("") || PreferencesHelper.getInstance().getString(this, "user_type").equals("1")) {
//                    onTabSelected(0);
//                }
//            }
//        }

    }

    @Override
    public void onTabUnselected(int position) {


        if (fragments != null) {
            if (position < fragments.size()) {
                FragmentManager fm = getSupportFragmentManager();
                FragmentTransaction ft = fm.beginTransaction();
                Fragment fragment = fragments.get(position);
                ft.remove(fragment);
                ft.commitAllowingStateLoss();
            }
        }


//        if (position == 0) {
//            if (PreferencesHelper.getInstance().getString(this, "token") == null || PreferencesHelper.getInstance().getString(this, "token").equals("")) {
////                toLogin(2);
//                bottomNavigationBar.getselectTab(0);
//            }
//            if (position == 2) {
//                if (PreferencesHelper.getInstance().getString(this, "user_type") == null || PreferencesHelper.getInstance().getString(this, "user_type").equals("") || PreferencesHelper.getInstance().getString(this, "user_type").equals("1")) {
////                    toLogin(2);
//                }
//            }
////            EventBus.getDefault().post(new FragmentTabEvent("1"));
//        }
    }

    @Override
    public void onTabReselected(int position) {

    }


    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        EventBus.getDefault().unregister(this);
        super.onStop();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(FragmentTabEvent event) {
        if (event.message.equals("1")) {
            bottomNavigationBar.selectTab(0);
        }
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        return super.dispatchTouchEvent(ev);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    private void getConfigList() {
        RestProxy.getInstance().getConfigList(PreferencesHelper.getInstance().getString(this, "token"), "14", new Observer<ConfigResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ConfigResponse configResponse) {
                System.out.println("showAreaDialog   " +  Integer.valueOf(configResponse.list.get(1).common_configuration_description));
                if (Integer.valueOf(configResponse.list.get(1).common_configuration_description) > Integer.valueOf(getVersionCode(HomeActivity.this))) {
                    apkUrl = configResponse.list.get(0).common_configuration_description;
                    showAreaDialog();
                }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }


    public String getVersionCode(Context context){
        PackageManager packageManager=context.getPackageManager();
        PackageInfo packageInfo;
        String versionCode="";
        try {
            packageInfo=packageManager.getPackageInfo(context.getPackageName(),0);
            versionCode=packageInfo.versionCode+"";
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }


    private void showAreaDialog() {
        if (updateFragment == null) {
            updateFragment = updateFragment.newInstance();
            updateFragment.show(getSupportFragmentManager(), "updateFragment");
            updateFragment.setmListener(new UpdateFragment.OnItemClickListener() {
                @Override
                public void onConfirm() {
                    DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(apkUrl));
                    File file = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "1.apk");
                    request.setDestinationUri(Uri.fromFile(file));
                    long downloadId = downloadManager.enqueue(request);
                    mApkPaths.put(downloadId,file.getAbsolutePath());
                    updateFragment.dismiss();
                }

                @Override
                public void onCancel() {
                    updateFragment.dismiss();
                }
            });
        } else if (!updateFragment.isAdded() && !updateFragment.isShowing()) {
            updateFragment.show(getSupportFragmentManager(), "updateFragment");
        }
    }


    class DownloadFinishReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //下载完成的广播接收者
            long completeDownloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            String apkPath = mApkPaths.get(completeDownloadId);
//            Log.d("DownloadFinishReceiver", apkPath);
            if (!apkPath.isEmpty()){
                setPermission(apkPath);//提升读写权限,否则可能出现解析异常
                installNormal(context,apkPath);
            }else {
//                Log.e("DownloadFinishReceiver", "apkPath is null");
            }
        }
    }

    private void setPermission(String filePath)  {
        String command = "chmod " + "777" + " " + filePath;
        Runtime runtime = Runtime.getRuntime();
        try {
            runtime.exec(command);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //普通安装
    private static void installNormal(Context context,String apkPath) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        //版本在7.0以上是不能直接通过uri访问的
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
            File file = (new File(apkPath));
            // 由于没有在Activity环境下启动Activity,设置下面的标签
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
            Uri apkUri = FileProvider.getUriForFile(context, "com.example.chenfengyao.installapkdemo", file);
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(new File(apkPath)),
                    "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }

}
